import { Component, OnInit } from '@angular/core';
import {OrderService} from '../order.service';
import {NzMessageService} from 'ng-zorro-antd';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  selector: 'app-deliver',
  templateUrl: './deliver.component.html',
  styleUrls: ['./deliver.component.scss'],
  providers: [OrderService]
})
export class DeliverComponent implements OnInit {

  order_no;
  expressInfo;
  validateForm: FormGroup;
  _isSpinning = true;
  courierList = [];

  constructor(private orderService: OrderService,
              private _message: NzMessageService,
              private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute) {
    this.validateForm = this.fb.group({
      express_id: [ '', [ Validators.required ] ],
      express_no: [ '', [ Validators.required ] ],
      order_no: [ '' ]
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  ngOnInit() {
    this.order_no = this.route.snapshot.params['id'];
    this.validateForm.controls['order_no'].setValue(this.order_no);
    this.getExpressInfo();
    this.getCourierList();
  }

  // 获取快递公司列表
  getCourierList() {
    this.orderService.getExpressList().subscribe(res => {
      if (res.code === 2000) {
        this.courierList = res.data.data;
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 获取发货信息
  getExpressInfo() {
    this.orderService.getExpressInfo(this.order_no).subscribe(res => {
      if (res.code === 2000) {
        this.expressInfo = res.data;
        this._isSpinning = false;
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    if (this.validateForm.valid) {
      this.orderService.editExpress(this.validateForm.value).subscribe(res => {
        if (res.code === 2000) {
          this._message.create('success', '发货成功');
          setTimeout(() => {
            this.router.navigate(['/member/order/list']);
          }, 1000);
        } else {
          this._message.create('error', res.message);
        }
      });
    }
  }
}
